//! # 生命周期管理模块
//! 
//! 本模块提供组件生命周期管理功能，包括启动顺序、依赖管理、优雅关闭等。
//! 采用面向接口编程设计，支持复杂的组件依赖关系管理和循环依赖检测。
//! 
//! ## 核心特性
//! 
//! - **依赖管理**: 自动解析组件依赖关系，按照拓扑顺序启动
//! - **循环检测**: 检测和防止组件间的循环依赖
//! - **生命周期钩子**: 支持在不同生命周期阶段执行自定义逻辑
//! - **优雅关闭**: 按照依赖顺序反向关闭组件，确保资源正确清理
//! - **异常恢复**: 支持组件启动失败后的恢复机制
//! 
//! ## 设计原则
//! 
//! 1. **面向接口编程**: 核心功能通过trait定义，便于扩展和测试
//! 2. **依赖分离**: 生命周期管理与具体组件实现分离
//! 3. **异常安全**: 在组件启动或停止失败时保证系统稳定性
//! 4. **性能优化**: 优化组件启动顺序，减少不必要的等待时间

use rustcloud_core::{ServiceResult, ServiceError};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use tokio::sync::RwLock;
use async_trait::async_trait;

// ============================================================================
// 核心接口定义 (Interface Layer)
// ============================================================================

/// 生命周期阶段
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum LifecyclePhase {
    Initialize,
    Start,
    Running,
    Stop,
    Destroy,
}

/// 生命周期钩子
#[async_trait]
pub trait LifecycleHook: Send + Sync {
    async fn execute(&self, phase: LifecyclePhase) -> ServiceResult<()>;
}

/// 生命周期管理器
pub struct LifecycleManager {
    components: Arc<RwLock<HashMap<String, Box<dyn LifecycleComponent>>>>,
    hooks: Arc<RwLock<HashMap<LifecyclePhase, Vec<Box<dyn LifecycleHook>>>>>,
    dependency_graph: Arc<RwLock<DependencyGraph>>,
}

#[async_trait]
pub trait LifecycleComponent: Send + Sync {
    async fn initialize(&self) -> ServiceResult<()>;
    async fn start(&self) -> ServiceResult<()>;
    async fn stop(&self) -> ServiceResult<()>;
    async fn destroy(&self) -> ServiceResult<()>;
    fn dependencies(&self) -> Vec<String> { Vec::new() }
    fn priority(&self) -> i32 { 0 }
}

/// 依赖图
pub struct DependencyGraph {
    nodes: HashSet<String>,
    edges: HashMap<String, Vec<String>>,
}

impl DependencyGraph {
    pub fn new() -> Self {
        Self {
            nodes: HashSet::new(),
            edges: HashMap::new(),
        }
    }

    pub fn add_node(&mut self, name: String) {
        self.nodes.insert(name);
    }

    pub fn add_dependency(&mut self, component: String, dependency: String) {
        self.edges.entry(component).or_insert_with(Vec::new).push(dependency);
    }

    pub fn topological_sort(&self) -> ServiceResult<Vec<String>> {
        let mut visited = HashSet::new();
        let mut temp_visited = HashSet::new();
        let mut result = Vec::new();

        for node in &self.nodes {
            if !visited.contains(node) {
                self.dfs_visit(node, &mut visited, &mut temp_visited, &mut result)?;
            }
        }

        result.reverse();
        Ok(result)
    }

    fn dfs_visit(
        &self,
        node: &str,
        visited: &mut HashSet<String>,
        temp_visited: &mut HashSet<String>,
        result: &mut Vec<String>,
    ) -> ServiceResult<()> {
        if temp_visited.contains(node) {
            return Err(ServiceError::ConfigurationError(format!("检测到循环依赖: {}", node)));
        }

        if visited.contains(node) {
            return Ok(());
        }

        temp_visited.insert(node.to_string());

        if let Some(dependencies) = self.edges.get(node) {
            for dep in dependencies {
                self.dfs_visit(dep, visited, temp_visited, result)?;
            }
        }

        temp_visited.remove(node);
        visited.insert(node.to_string());
        result.push(node.to_string());

        Ok(())
    }
}

impl LifecycleManager {
    pub fn new() -> Self {
        Self {
            components: Arc::new(RwLock::new(HashMap::new())),
            hooks: Arc::new(RwLock::new(HashMap::new())),
            dependency_graph: Arc::new(RwLock::new(DependencyGraph::new())),
        }
    }

    pub async fn register_component(
        &self,
        name: String,
        component: Box<dyn LifecycleComponent>,
    ) -> ServiceResult<()> {
        let dependencies = component.dependencies();
        
        {
            let mut graph = self.dependency_graph.write().await;
            graph.add_node(name.clone());
            for dep in dependencies {
                graph.add_dependency(name.clone(), dep);
            }
        }

        {
            let mut components = self.components.write().await;
            components.insert(name.clone(), component);
        }

        tracing::info!("组件注册成功: {}", name);
        Ok(())
    }

    pub async fn start_all(&self) -> ServiceResult<()> {
        let startup_order = {
            let graph = self.dependency_graph.read().await;
            graph.topological_sort()?
        };

        self.execute_hooks(LifecyclePhase::Initialize).await?;

        for component_name in &startup_order {
            let components = self.components.read().await;
            if let Some(component) = components.get(component_name) {
                tracing::info!("初始化组件: {}", component_name);
                component.initialize().await?;
            }
        }

        self.execute_hooks(LifecyclePhase::Start).await?;

        for component_name in &startup_order {
            let components = self.components.read().await;
            if let Some(component) = components.get(component_name) {
                tracing::info!("启动组件: {}", component_name);
                component.start().await?;
            }
        }

        self.execute_hooks(LifecyclePhase::Running).await?;
        tracing::info!("所有组件启动完成");
        Ok(())
    }

    pub async fn stop_all(&self) -> ServiceResult<()> {
        let startup_order = {
            let graph = self.dependency_graph.read().await;
            graph.topological_sort()?
        };

        self.execute_hooks(LifecyclePhase::Stop).await?;

        // 反向停止
        for component_name in startup_order.iter().rev() {
            let components = self.components.read().await;
            if let Some(component) = components.get(component_name) {
                tracing::info!("停止组件: {}", component_name);
                let _ = component.stop().await;
            }
        }

        for component_name in startup_order.iter().rev() {
            let components = self.components.read().await;
            if let Some(component) = components.get(component_name) {
                tracing::info!("销毁组件: {}", component_name);
                let _ = component.destroy().await;
            }
        }

        self.execute_hooks(LifecyclePhase::Destroy).await?;
        tracing::info!("所有组件停止完成");
        Ok(())
    }

    pub async fn add_hook(&self, phase: LifecyclePhase, hook: Box<dyn LifecycleHook>) {
        let mut hooks = self.hooks.write().await;
        hooks.entry(phase).or_insert_with(Vec::new).push(hook);
    }

    async fn execute_hooks(&self, phase: LifecyclePhase) -> ServiceResult<()> {
        let hooks = self.hooks.read().await;
        if let Some(phase_hooks) = hooks.get(&phase) {
            for hook in phase_hooks {
                hook.execute(phase.clone()).await?;
            }
        }
        Ok(())
    }
}

impl Default for LifecycleManager {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    struct TestComponent {
        name: String,
        dependencies: Vec<String>,
    }

    impl TestComponent {
        fn new(name: String, dependencies: Vec<String>) -> Self {
            Self { name, dependencies }
        }
    }

    #[async_trait]
    impl LifecycleComponent for TestComponent {
        async fn initialize(&self) -> ServiceResult<()> {
            tracing::info!("初始化组件: {}", self.name);
            Ok(())
        }

        async fn start(&self) -> ServiceResult<()> {
            tracing::info!("启动组件: {}", self.name);
            Ok(())
        }

        async fn stop(&self) -> ServiceResult<()> {
            tracing::info!("停止组件: {}", self.name);
            Ok(())
        }

        async fn destroy(&self) -> ServiceResult<()> {
            tracing::info!("销毁组件: {}", self.name);
            Ok(())
        }

        fn dependencies(&self) -> Vec<String> {
            self.dependencies.clone()
        }
    }

    #[tokio::test]
    async fn test_lifecycle_manager() {
        let manager = LifecycleManager::new();

        // 注册组件
        manager.register_component(
            "registry".to_string(),
            Box::new(TestComponent::new("registry".to_string(), vec![])),
        ).await.unwrap();

        manager.register_component(
            "loadbalancer".to_string(),
            Box::new(TestComponent::new("loadbalancer".to_string(), vec!["registry".to_string()])),
        ).await.unwrap();

        // 启动所有组件
        manager.start_all().await.unwrap();

        // 停止所有组件
        manager.stop_all().await.unwrap();
    }
}